class Solution
{
public:
    int minCut(string s)
    {
        int n = s.size();
        vector<vector<bool>> f(n, vector<bool>(n));
        for (int i = n - 1; i >= 0; i--)
            for (int j = i; j < n; j++)
                if (s[i] == s[j])
                    f[i][j] = i + 1 < j ? f[i + 1][j - 1] : true;

        vector<int> g(n, INT_MAX);
        for (int i = 0; i < n; i++)
        {
            if (f[0][i]) g[i] = 0;
            else
            {
                for (int j = 1; j <= i; j++)
                    if (f[j][i])
                        g[i] = min(g[i], g[j - 1] + 1);
            }
        }
        return g[n - 1];
    }
};